# backend/app/api/api_exception_handler.py

from fastapi import FastAPI, Request, HTTPException, status
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from starlette.status import HTTP_404_NOT_FOUND
from app.utils.logger import get_logger
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.api.api_model import ErrorResponse  # 引入错误响应模型

logger = get_logger()

def register_exception_handlers(app: FastAPI):
    @app.exception_handler(RequestValidationError)
    async def request_validation_exception_handler(request: Request, exc: RequestValidationError):
        logger.error(f"Validation error for request {request.method} {request.url}: {exc}")
        errors = [
            {
                "loc": err["loc"],
                "msg": err["msg"],
                "type": err["type"]
            }
            for err in exc.errors()
        ]
        return JSONResponse(
            status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
            content=ErrorResponse(
                status="error",
                message="请求参数验证失败",
            ).dict()
        )
    
    @app.exception_handler(StarletteHTTPException)
    async def http_exception_handler(request: Request, exc: StarletteHTTPException):
        if exc.status_code == HTTP_404_NOT_FOUND:
            logger.error(f"请求的地址不存在: {request.url}")
            return JSONResponse(
                status_code=status.HTTP_404_NOT_FOUND,
                content=ErrorResponse(
                    status="error",
                    message="请求的地址不存在",
                ).dict()
            )
        # 处理其他 HTTPException
        logger.error(f"HTTPException: {exc.status_code} {exc.detail}")
        return JSONResponse(
            status_code=exc.status_code,
            content=ErrorResponse(
                status="error",
                message=exc.detail,
            ).dict()
        )
    
    @app.exception_handler(Exception)
    async def unhandled_exception_handler(request: Request, exc: Exception):
        logger.error(f"Unhandled exception: {exc}")
        return JSONResponse(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            content=ErrorResponse(
                status="error",
                message="服务器内部错误",
            ).dict()
        )